package cn.tedu._06article.controller;

import cn.tedu._06article.base.response.JsonResult;
import cn.tedu._06article.base.response.StatusCode;
import cn.tedu._06article.mapper.UserMapper;
import cn.tedu._06article.pojo.dto.UserArticleParam;
import cn.tedu._06article.pojo.dto.UserLoginParam;
import cn.tedu._06article.pojo.entity.Article;
import cn.tedu._06article.pojo.vo.UserArticleVO;
import cn.tedu._06article.pojo.vo.UserVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;

@Validated
@Slf4j
@Api(tags = "01.用户模块")
@RestController
@RequestMapping("/v1/user/")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @PostMapping("login")
    @ApiOperation("登录功能")
    @ApiOperationSupport(order = 10)
    public JsonResult login(@RequestBody UserLoginParam userLoginParam, @ApiIgnore HttpSession session){
        log.debug("userLoginParam = " + userLoginParam);
        String username = userLoginParam.getUsername();
        String password = userLoginParam.getPassword();
        UserVO userVO = userMapper.selectByUsernameAndPassword(username, password);
        if (userVO == null){
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        }

        session.setAttribute("user", userVO);
        return JsonResult.ok();
    }

    @PostMapping("article")
    @ApiOperation("发表文章")
    @ApiOperationSupport(order = 20)
    public JsonResult article(@RequestBody @Validated UserArticleParam userArticleParam, @ApiIgnore HttpSession session){
        log.debug("userArticleParam = " + userArticleParam);

        UserVO userVO = (UserVO) session.getAttribute("user");

        Article article = new Article();
        BeanUtils.copyProperties(userArticleParam, article);
        article.setUserId(userVO.getId());
        log.debug("article = " + article);
        userMapper.insertArticle(article);

        return JsonResult.ok();
    }

    @GetMapping("selectByArticleId")
    @ApiOperation("查询文章")
    @ApiOperationSupport(order = 30)
    public JsonResult selectByArticleId(@Range(min = 1, max = 100, message = "文章编号必须在1-100之间") @RequestParam Integer id){
        log.debug("id = " + id);
        UserArticleVO userArticleVO = userMapper.selectByArticleId(id);

        return JsonResult.ok(userArticleVO);
    }
}










